package com.example.service.impl;

import com.example.algorithm.SnowflakeIdWorker;
import com.example.dto.SentenceResult;
import com.example.entity.Record;
import com.example.entity.Sentence;
import com.example.entity.Topic;
import com.example.repository.RecordRepository;
import com.example.repository.SentenceRepository;
import com.example.service.RecordService;
import com.example.service.SentenceService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordRepository recordRepository;
    @Autowired
    private SentenceService sentenceService;
    @Autowired
    private UserService userService;

    @Override
    public List<Record> getRecordsByUserIdSortByTime(String userId){
        List<Record> list = recordRepository.findByUserId(userId);
        Collections.sort(list, new Comparator<Record>() {
            @Override
            public int compare(Record o1, Record o2) {
                if(o1.getCreateAt().before(o2.getCreateAt()))
                    return 1;
                else
                    return -1;
            }
        });
        perfectRecord(list);
        return list;
    }

    @Override
    public List<Record> getRecordsByUserIdSortByGrade(String userId){
        List<Record> list = recordRepository.findByUserId(userId);
        Collections.sort(list, new Comparator<Record>() {
            @Override
            public int compare(Record o1, Record o2) {
                if(o1.getGrade()<o2.getGrade())
                    return 1;
                else
                    return -1;
            }
        });
        perfectRecord(list);
        return list;
    }

    @Override
    public Record findByUserIdAndSentenceId(String userId, String sentenceId) {
        return recordRepository.findByUserIdAndSentenceId(userId, sentenceId);
    }

    @Override
    public void saveRecord(Record record) {
        recordRepository.save(record);
    }

    @Override
    public double saveRecord(List<SentenceResult> sentenceResults, String userId, String sentenceId) {
        String sentenceAndGrade = "";
        for (SentenceResult sentenceResult:sentenceResults
        ) {
            String temp = sentenceResult.getSentence() + "<" + sentenceResult.getScore() +"<";
            sentenceAndGrade += temp;
        }
        //保存记录到数据库
        Record record = new Record();
        record.setId(SnowflakeIdWorker.generateId()+"");
        record.setGrade((int)Math.round(sentenceResults.get(0).getScore()));
        record.setUserId(userId);
        record.setSentenceId(sentenceId);
        record.setCreateAt(new Date());
        record.setCreateBy("admin");
        record.setUpdateAt(new Date());
        record.setUpdateBy("admin");
        record.setDel(false);
        record.setSentenceAndGrade(sentenceAndGrade);
        Record record1 = findByUserIdAndSentenceId(record.getUserId(),record.getSentenceId());
        double highScore = record.getGrade();
        if (record1!=null){
            //只保存最高分的记录
            if(record1.getGrade() <= record.getGrade()) {
                record.setId(record1.getId());
                record.setCreateAt(record1.getCreateAt());
                record.setCreateBy(record1.getCreateBy());
                saveRecord(record);
            }else{
                highScore = record1.getGrade();
            }
        }else {
            saveRecord(record);
            userService.addLevel(userId);
        }
        //用户表句子数+1
        userService.addRecord(userId);
        return highScore;
    }

    /**
     * 根据数据库保存的句子id、主题id、sentenceAndGrade，完善Record的详细信息
     * @param list 数据库读取出来的数据
     */
    private void perfectRecord(List<Record> list){
        Sentence sentence;
        ArrayList<SentenceResult> results;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        for (Record r : list
        ) {
            sentence = sentenceService.getSentenceById(r.getSentenceId());
            results = handle(r.getSentenceAndGrade());
            r.setSentenceContent(results.get(0).getSentence());
            results.remove(0);
            r.setSentenceResults(results);
            r.setTopicName(sentence.getTopicName());
            r.setCreateAtFormat(simpleDateFormat.format(r.getCreateAt()));
            r.setUpdateAtFormat(simpleDateFormat.format(r.getUpdateAt()));
        }
    }

    /**
     * 把数据库中的字符串sentenceAndGrade解释成数组形式
     * @param sentenceAndGrade 数据库里面存储的字符串
     * @return 返回给前端的格式
     */
    private ArrayList<SentenceResult> handle(String sentenceAndGrade){
        ArrayList<SentenceResult> results = new ArrayList<>();
        String[] strings = sentenceAndGrade.split("<");
        String temp = "";
        for (int i = 0; i < strings.length; ) {
            SentenceResult sentenceResult = new SentenceResult();
            temp = strings[i];
            sentenceResult.setSentence(temp);
            i ++;
            temp = strings[i];
            try {
                sentenceResult.setScore(Double.parseDouble(temp));
            }catch (Exception e){
                e.printStackTrace();
            }
            results.add(sentenceResult);
            i ++;
        }
        return results;
    }

}

